package com.hmsg.health.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 编码与解码操作工具类
 *
 * @author
 * @since 1.0
 */
public class CodecUtil {
	private static Logger logger = LoggerFactory.getLogger(CodecUtil.class);
	private static final String CHARSET = "UTF-8";

	/**
	 * 将 URL 编码
	 */
	public static String encodeURL(String str) {
		String target;
		try {
			target = URLEncoder.encode(str, CHARSET);
		} catch (Exception e) {
			logger.error("编码出错！", e);
			throw new RuntimeException(e);
		}
		return target;
	}

	/**
	 * 将 URL 解码
	 */
	public static String decodeURL(String str) {
		String target;
		try {
			target = URLDecoder.decode(str, CHARSET);
		} catch (Exception e) {
			logger.error("解码出错！", e);
			throw new RuntimeException(e);
		}
		return target;
	}

	/**
	 * 将字符串 Base64 编码
	 */
	public static String encodeBASE64(String str) {
		String target;
		try {
			target = Base64.encodeBase64URLSafeString(str.getBytes(CHARSET));
		} catch (UnsupportedEncodingException e) {
			logger.error("编码出错！", e);
			throw new RuntimeException(e);
		}
		return target;
	}

	/**
	 * 将字符串 Base64 解码
	 */
	public static String decodeBASE64(String str) {
		String target;
		try {
			target = new String(Base64.decodeBase64(str), CHARSET);
		} catch (UnsupportedEncodingException e) {
			logger.error("解码出错！", e);
			throw new RuntimeException(e);
		}
		return target;
	}

	/**
	 * 将字符串 MD5 加密
	 */
	public static String encryptMD5(String str) {
		return DigestUtils.md5Hex(str);
	}

	/**
	 * 将字符串 SHA 加密
	 */
	public static String encryptSHA(String str) {
		return DigestUtils.sha1Hex(str);
	}

	/**
	 * 获取 UUID（32位）
	 */
	public static String createUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
	}

	public static void main(String[] args) {
		System.out.println(encryptMD5("TOKENXXXX" + "/orders/2" + "1495091075740"));
		System.out.println(encodeBASE64("TOKENXXXX&" + "1495091075740" + "&73b11f62998ee7b4f82082c70dfe7fcf"));
	}
}
